<?php

namespace utils\wechat;

use EasyWeChat\Factory;
use think\facade\Log;

class SubscribeService
{

    /**
     * 小程序模板消息
     * @param string openid  用openid
     * @param string template_id 模板消息ID 直接到微信公众平台模板消息里面去查看
     * @param string url 模板消息的跳转地址 可以留空
     * @param string body 模板消息详情
     * $data['openid']        = 'oCKGm5MFwS-Uy3VLbmV46O-C4sy4';
     * $data['form_id']    = $this->_data['form_id'];
     * $data['body'] = [
     * "keyword1"   => "20元",
     * "keyword2"   => "武汉站东广场",
     * "keyword3"   => "鄂A54M57",
     * "keyword4"   => date('Y-m-d H:i:s'),
     * "keyword5"   => '5小时',
     * ];
     * @return array   返回发送详情
     */
    public function sendMiniSubscribeMsg($data)
    {

        $app = Factory::miniProgram(config('wechat.default.mini_program'));

        $param['touser'] = $data['openid'];
        $param['template_id'] = $data['template_id'];
        $param['page'] = $data['page'];
        $param['data'] = $data['data'];

        try {
            $res = $app->subscribe_message->send($param);
        } catch (\Exception $e) {
            log::error('模板消息发送错误：' . print_r($e->getMessage()));
            throw new \Exception('发送失败');
        }

        return $res;
    }
}